package com.junlong0716.enjoylearning.ui

import android.Manifest
import android.content.Intent
import android.content.pm.ActivityInfo
import android.net.Uri
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.ToastUtils
import com.htxcsoft.corelibrary.glide.GlideUtils
import com.junlong0716.enjoylearning.CommentPresenter
import com.junlong0716.enjoylearning.MyApp
import com.junlong0716.enjoylearning.R
import com.junlong0716.enjoylearning.dialog.LoadingDialog
import com.junlong0716.enjoylearning.entity.ClassifyEntity
import com.junlong0716.enjoylearning.entity.rxevent.UploadFileProgressEvent
import com.junlong0716.enjoylearning.entity.rxevent.UploadFileSucceedEvent
import com.junlong0716.enjoylearning.manager.MatisseGlideManager
import com.junlong0716.module.common.rxbus.RxBus
import com.junlong0716.module.common.rxbus.Subscribe
import com.junlong0716.module.common.rxbus.ThreadMode
import com.junlong0716.module.common.utils.Uri2PathUtils
import com.orhanobut.logger.Logger
import com.tbruyelle.rxpermissions2.RxPermissions
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import com.zhy.view.flowlayout.FlowLayout
import com.zhy.view.flowlayout.TagAdapter
import kotlinx.android.synthetic.main.activity_upload_audio.*
import kotlinx.android.synthetic.main.view_title_bar.*
import java.io.File


class UploadAudioActivity : AppCompatActivity() {
    private val REQUEST_CODE_CHOOSE = 0xffaf
    private val REQUEST_CODE_FILE = 0xffaa
    private var isGranted = false
    private var mSelected: List<Uri>? = null
    private var photoPathFromContentUri: String = ""
    private var filePath: File? = null
    private lateinit var mFile: File
    private lateinit var loadingDialog: LoadingDialog
    private var uploadType = 0
    private var hasSelected = false
    private lateinit var knowledgeType: ArrayList<ClassifyEntity.DetailsBean>
    private lateinit var pickerIntent: Intent
    private lateinit var knowledgeClassify: ArrayList<Int>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_upload_audio)
        val bundle = intent.extras
        uploadType = bundle.getInt("UPLOAD_TYPE")
        RxBus.getDefault().register(this)
        requestPermission()
        initView()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun eventBus(s: UploadFileProgressEvent) {
        when (s.code) {
            0x12ff -> {
                loadingDialog.setProgress("上传${s.uploadType}\n${s.progress}%")
            }
            else -> {
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun eventBus(s: UploadFileSucceedEvent) {
        when (s.code) {
            0x13ff -> {
                loadingDialog.dismiss()
                ToastUtils.showShort("文件上传成功！")
                finish()
            }
            else -> {
            }
        }
    }

    private fun requestPermission() {
        val rxPermissions = RxPermissions(this)
        rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe { granted ->
                    isGranted = if (granted) {
                        true
                    } else {
                        ToastUtils.showShort("请允许获取权限！")
                        false
                    }
                }
    }

    private fun initView() {

        if (uploadType == 3) {
            bt_image_picker.visibility = View.GONE
            bt_picker_audio.visibility = View.GONE
            det_content.visibility = View.VISIBLE
        }

        if (uploadType == 2){
            det_content.visibility = View.VISIBLE
        }

        mSelected = ArrayList()

        rl_back.setOnClickListener { finish() }

        pickerIntent = Intent(Intent.ACTION_GET_CONTENT)
        pickerIntent.addCategory(Intent.CATEGORY_OPENABLE)

        when (uploadType) {
            1 -> {
                tv_title.text = "上传视频"
                bt_picker_audio.text = "请选择视频文件"
                //intent.setType(“image/*”);//选择图片
                pickerIntent.setType("video/*"); //选择视频 （mp4 3gp 是android支持的视频格式）
                //intent.setType(“video/*;image/*”);//同时选择视频和图片
                //intent.type = "*/*"//无类型限制

            }

            2 -> {
                pickerIntent.type = "audio/*" //选择音频
                tv_title.text = "上传音频"
                bt_picker_audio.text = "请选择音频文件"
            }

            3 -> {
                tv_title.text = "上传文稿"
                bt_picker_audio.text = "请选择附件文件"
                pickerIntent.type = "*/*"//无类型限制
            }


        }

        bt_type.setOnClickListener {
            //创建需要对应于目标Activity的Intent
            val intent = Intent(this, AddTypeActivity::class.java)
            //启动指定Activity并等待返回的结果,其中0是请求码,用于标识该请求


            if (hasSelected) {
                val bundle = Bundle()
                bundle.putSerializable("HAS_SELECTED_TYPES", knowledgeType)
                intent.putExtras(bundle)
            }

            startActivityForResult(intent, 0)
        }



        bt_picker_audio.setOnClickListener {
            startActivityForResult(pickerIntent, REQUEST_CODE_FILE)
        }
        bt_image_picker.setOnClickListener {
            if (isGranted) {
                Matisse.from(this)
                        .choose(MimeType.allOf())
                        .countable(true)
                        .maxSelectable(1)
                        //.addFilter(GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
                        .gridExpectedSize(resources.getDimensionPixelSize(R.dimen.grid_expected_size))
                        .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                        .thumbnailScale(0.85f)
                        .imageEngine(MatisseGlideManager())
                        .forResult(REQUEST_CODE_CHOOSE)
            } else {
                requestPermission()
            }
        }

        bt_upload.setOnClickListener {
            val knowledgeTitle = det_title.text.toString().trim()
            val knowledgeDescribe = det_describe.text.toString().trim()

            var knowledgeContent = ""

            if (TextUtils.isEmpty(knowledgeTitle) || TextUtils.isEmpty(knowledgeDescribe)) {
                ToastUtils.showShort("知识标题或知识描述不能为空！")
                return@setOnClickListener
            }


            //判断是否是文稿类别
            if (uploadType == 3) {
                knowledgeContent = det_content.text.toString().trim()
                if (knowledgeContent == "") {
                    ToastUtils.showShort("请输入知识内容！")
                    return@setOnClickListener
                }
            }

            if (uploadType == 2){
                knowledgeContent = det_content.text.toString().trim()
                if (knowledgeContent == "") {
                    ToastUtils.showShort("请输入知识内容！")
                    return@setOnClickListener
                }
            }


            if (uploadType != 3) {
                if (filePath == null) {
                    ToastUtils.showShort("请选择文件！")
                    return@setOnClickListener
                }
            }

            if (uploadType != 3) {
                if (photoPathFromContentUri == "") {
                    ToastUtils.showShort("请选择封面图片！")
                    return@setOnClickListener
                }
            }


            val commentPresenter = CommentPresenter()

            loadingDialog = LoadingDialog(this)
            loadingDialog.setCanceledOnTouchOutside(false)
            loadingDialog.show()

            knowledgeClassify = ArrayList()

            for (i in 0 until knowledgeType.size) {
                knowledgeClassify.add(knowledgeType[i].id)
            }

            if (uploadType == 3) {
                commentPresenter.requestAddDocumentKnowledge(this, MyApp.instance().userAccount!!.id, uploadType, knowledgeTitle, knowledgeDescribe, knowledgeClassify, knowledgeContent)
            } else {
                commentPresenter.requestUpload(this, MyApp.instance().userAccount!!.id, uploadType, knowledgeTitle, knowledgeDescribe, FileUtils.getFileByPath(photoPathFromContentUri), filePath!!, knowledgeClassify,knowledgeContent)
            }
        }


    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            val obtainResult = Matisse.obtainResult(data)
            if (!obtainResult.isEmpty()) {
                iv_img.visibility = View.VISIBLE
                GlideUtils.showImageFade(this, obtainResult[0], iv_img)
                photoPathFromContentUri = Uri2PathUtils.getPhotoPathFromContentUri(this, obtainResult[0])
//                OkGo.post<String>(NetConstant.REQUEST_HEADER + NetApi.API_UPLOAD_FILE)
//                        .tag(this)
//                        .params("file1",FileUtils.getFileByPath(photoPathFromContentUri))
//                        .execute(object :StringCallback(){
//                            override fun onSuccess(response: Response<String>?) {
//
//                            }
//
//                            override fun uploadProgress(progress: Progress?) {
//
//                            }
//                        })
            }
        }

        if (requestCode == REQUEST_CODE_FILE && resultCode == RESULT_OK) {
            val uri = data!!.data
            val filePathFromUri = Uri2PathUtils.getPhotoPathFromContentUri(this, uri)
            Logger.e(filePathFromUri)
            filePath = FileUtils.getFileByPath(filePathFromUri)
            tv_file_name.text = filePath!!.name
            mFile = File(filePathFromUri)

//            OkGo.post<String>(NetConstant.REQUEST_HEADER + NetApi.API_UPLOAD_FILE)
//                    .tag(this)
//                    .params("file", filePath)
//                    .execute(object : StringCallback() {
//                        override fun onSuccess(response: Response<String>?) {
//                            ToastUtils.showShort("上传成功！")
//                        }
//
//                        override fun uploadProgress(progress: Progress?) {
//                            Logger.e(progress!!.fraction.toString())
//                        }
//
//                        override fun onError(response: Response<String>?) {
//                            Logger.e("上传失败！")
//                        }
//                    })
        }

        if (requestCode == 0 && resultCode == 0) {
            if (data == null) {
                return
            }

            bt_type.text = "修改分类"

            //取出Intent里的Extras数据
            val bundle = data!!.extras
            //取出Bundle中的数据
            knowledgeType = bundle.getSerializable("KNOWLEDGE_TYPES") as ArrayList<ClassifyEntity.DetailsBean>

            if (knowledgeType.isEmpty()) {
                flow_layout.visibility = View.GONE
                return
            }

            hasSelected = true

            flow_layout.visibility = View.VISIBLE

            flow_layout.adapter = object : TagAdapter<ClassifyEntity.DetailsBean>(knowledgeType) {
                override fun getView(parent: FlowLayout?, position: Int, t: ClassifyEntity.DetailsBean?): View {
                    val tagView = LayoutInflater.from(this@UploadAudioActivity).inflate(R.layout.item_tag, null)
                    val tvTag = tagView.findViewById<TextView>(R.id.tv_tag)
                    tvTag.text = t!!.classifyName
                    return tagView
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (RxBus.getDefault().isRegistered(this)) {
            RxBus.getDefault().unregister(this)
        }
    }
}
